package com.xbongbong.helper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.enums.ReleaseState;
import com.xbongbong.enums.Status;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.util.HeaderUtil;
import com.xbongbong.util.HttpRequestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 处理流程相关的内容
 *
 * @ClassName ProcessHelper
 * @Author 梁鲁江
 * 创建时间 2022/6/17 9:11
 * 修改时间  2022/6/17 9:11
 **/
@Component
public class ProcessDefinitionHelper {
    private static final Log log = LogFactory.getLog(ProcessDefinitionHelper.class);
    /**
     * 
     * @param projectCode
     * @param name
     * @param description
     * @param globalParams
     * @param locations
     * @param timeout
     * @param tenantCode
     * @param taskRelationJson
     * @param taskDefinitionJson  一个节点task只能被使用一次
     * @return  返回ProcessCode
     */
    public  Long  createProcessDefinition(
            long projectCode,
            String name,
            String description,
            String globalParams,
            String locations,
            int timeout,
            String tenantCode,
            String taskRelationJson,
            String taskDefinitionJson) throws XbbException {
        
//        /dolphinscheduler/projects/5881692604416/process-definition
        String url = HeaderUtil.getHosts()+"/dolphinscheduler/projects/" +
                projectCode +
                "/process-definition";
        JSONObject requestData = new JSONObject();
        requestData.put("name",name);
        requestData.put("description",description);
        requestData.put("globalParams",globalParams);
        requestData.put("locations",locations);
        requestData.put("timeout",timeout);
        requestData.put("tenantCode",tenantCode);
        requestData.put("taskRelationJson",taskRelationJson);
        requestData.put("taskDefinitionJson",taskDefinitionJson);
        //返回值 {"code":0,"msg":"success","data":{"id":0,"code":5958932994464,"name":"DAG插入接口测试","version":0,"releaseState":null,"projectCode":5958932883360,"description":"我是描述","globalParams":"[]","globalParamList":null,"globalParamMap":{},"createTime":"2022-06-23 19:42:44","updateTime":"2022-06-23 19:42:44","flag":"YES","userId":1,"userName":null,"projectName":null,"locations":"[{\"taskCode\":5958932983072,\"x\":0,\"y\":0}]","scheduleReleaseState":null,"timeout":0,"tenantId":5,"tenantCode":null,"modifyBy":null,"warningGroupId":0},"failed":false,"success":true}
        String ret = HttpRequestUtils.post(url, requestData);
        JSONObject result = JSON.parseObject(ret);
        Integer code = result.getInteger("code");
        if(Objects.equals(code, Status.SUCCESS.getCode())){
           return result.getJSONObject("data").getLong("code");
        }else {
            log.error(ErrorCodeEnum.API_ERROR_263001);
            throw  new XbbException(ErrorCodeEnum.API_ERROR_263001);
        }
    }

    /**
     * 流程上下线操作
     * @param projectCode 项目code  
     * @param processCode 流程code
     * @param releaseStateCode  
     * @see com.xbongbong.enums.ReleaseState
     * @return
     */
    public  String releaseProcessDefinition( long projectCode, long processCode, Integer releaseStateCode) throws XbbException {
        String url = HeaderUtil.getHosts()+"/dolphinscheduler/projects/" +
                projectCode +
                "/process-definition/" + processCode + "/release";
        JSONObject requestData = new JSONObject();
        requestData.put("releaseState", Objects.requireNonNull(ReleaseState.getEnum(releaseStateCode)).getUpDescp());
        //name非必填（API文档里给了必填）
//        requestData.put("name","DAG插入测试");
        String ret = HttpRequestUtils.post(url, requestData);
        JSONObject result = JSON.parseObject(ret);
        Integer code = result.getInteger("code");
        if(Objects.equals(code, Status.SUCCESS.getCode())){
           
        }else {
            log.error(ErrorCodeEnum.API_ERROR_263001 + ReleaseState.getEnum(releaseStateCode).getDescp() );
            throw  new XbbException(ErrorCodeEnum.API_ERROR_263001,String.format(ErrorCodeEnum.API_ERROR_263001.getMsg(), ReleaseState.getEnum(releaseStateCode).getDescp()));
        }
        return "";
    }

    public static void main(String[] args) {
     /*   createProcessDefinition(5881692604416L,"DAG11","","[]","[{\"taskCode\":5932197591168,\"x\":498,\"y\":200}]",0,"default",
                "[{\"name\":\"\",\"preTaskCode\":0,\"preTaskVersion\":0,\"postTaskCode\":5932197591168,\"postTaskVersion\":0,\"conditionType\":0,\"conditionParams\":{}}]",
                "[{\"code\":5932197591168,\"name\":\"task测试6\",\"description\":\"\",\"taskType\":\"SQL\",\"taskParams\":{\"type\":\"CLICKHOUSE\",\"datasource\":1,\"sql\":\"SELECT * from tb_saas_customer_communicate  limit 1\",\"udfs\":\"\",\"sqlType\":\"0\",\"sendEmail\":false,\"displayRows\":10,\"title\":\"\",\"groupId\":null,\"localParams\":[],\"connParams\":\"\",\"preStatements\":[],\"postStatements\":[],\"dependence\":{},\"conditionResult\":{\"successNode\":[],\"failedNode\":[]},\"waitStartTimeout\":{},\"switchResult\":{}},\"flag\":\"YES\",\"taskPriority\":\"MEDIUM\",\"workerGroup\":\"default\",\"failRetryTimes\":\"0\",\"failRetryInterval\":\"1\",\"timeoutFlag\":\"CLOSE\",\"timeoutNotifyStrategy\":\"\",\"timeout\":0,\"delayTime\":\"0\",\"environmentCode\":-1}]"
                );*/
//        releaseProcessDefinition(5958932883360L,5958932994464L,1);
    }
}
